package collector;

import javax.jms.JMSException;
import javax.naming.NamingException;

import database.CassandraProxy;
import messaging.SubscriberGateway;

public class StatusReceiver {

	// Subscriber gateway used to listen to a given subscription
	private SubscriberGateway gateway;
	
	/**
	 * Set up a temporary receiver of JMXData using a given connectionFactory and destination.
	 * @param statusListener		Implementation of MessageListener which defines what to do with incoming messages.
	 * @param connectionFactoryName	The name of a connection factory exposed by the JMS provider.
	 * @param destinationName		The name of a JMS topic the receiver is meant to listen to. Each monitored application sends data to one topic.
	 */
	public StatusReceiver(StatusListener statusListener, String connectionFactoryName, String destinationName){
		try {
			gateway = new SubscriberGateway(connectionFactoryName, destinationName);
			System.out.println("registered subscriber, destination = " + destinationName);
			gateway.registerSubscriber(statusListener);
		} catch (NamingException | JMSException e) {
		} 
	}

	/**
	 * This method must be called when an instance of JMXDataReceiver is no longer needed.
	 */
	public void stop() {
		if (gateway != null)
			gateway.close();
	}
	
	@Override
	public void finalize() {
		this.stop();
	}
	
	public static void main(String[] args) throws InterruptedException {
		String jmsConnectionFactory = "ConnectionFactory";
		String jmsTopic = "topic1";
		new StatusReceiver(new DatabaseStatusSaver(new CassandraProxy()), jmsConnectionFactory, jmsTopic);
	}

}
